<script setup lang="ts">
/**
 * @see {@link https://vuejs.org/api/sfc-script-setup.html#defineoptions}
 */
import Editor from "@/components/WangEditor/index.vue";
import { getSourceList, getCategoryList, saveSource, getTaskDel, getSourceEdit } from "@/api/curriculum/index";
import { materialQuery, PageVO, addCurriculumForm } from "@/api/curriculum/types";
import type { FormInstance, FormRules } from 'element-plus'

// 图片域名
const imgUrl = ref(import.meta.env.VITE_APP_BASE_API);

defineOptions({
  name: "User",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm); // 查询表单

const loading = ref(false);
const total = ref(0);

const queryParams = reactive<materialQuery>({
  page: 1,
  page_size: 14,
});

const userList = ref<PageVO[]>();


/**
 * 查询
 */
function handleQuery() {
  loading.value = true;
  getSourceList(queryParams)
    .then(({ data }) => {
      userList.value = data.data;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.page = 1;
  handleQuery();
}

// 弹窗数据
const dialog = reactive({
  visible: false,
  title: "新增",
})


// 获取素材分类顶级列表
const selectList = ref<any[]>([])

// 打开新增弹窗
const hanldeOpenDialog = (data: any | null = null) => {
  dialog.visible = true;
  dialog.title = "新增";

  if (data) {
    console.log(data)
    formData.id = data.id;
    formData.title = data.title;
    formData.pid = data.pid;
    formData.type = data.type;
    formData.image = data.image;
    formData.url = imgUrl.value + data.image;
    formData.link = data.link;
    formData.content = data.content;
    formData.detail = data.detail;
    formData.sort = data.sort;
    dialog.title = "编辑";
  }

  getCategoryList({}).then(({ data }) => {
    selectList.value = data;
  })
}

// 提交数据
const formData = reactive<addCurriculumForm>({
  title: '',
  pid: '',
  type: 1,
  link: '',
  image: '',
  content: '',
  detail: '',
  url: '',
  sort: 0,
})

const ruleFormRef = ref(ElForm); // 新增表单
// 提交正则
const rules = reactive<FormRules>({
  title: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  pid: [{ required: true, message: '请选择顶级分类', trigger: 'change' }]
})

// 获取url 路径
const updatepostUrl = (url: string) => {
  formData.image = url;
  formData.url = imgUrl.value + url;
}

// 新增修改弹框
const handleSubmit = async () => {
  await ruleFormRef.value.validate(async (valid: any) => {
    if (valid) {
      if (dialog.title == "编辑") {
        let res = await getSourceEdit(formData) as any;
        ElMessage.success(res.msg);
        closeDialog()
        resetQuery()
      } else {
        let res = await saveSource(formData) as any;
        ElMessage.success(res.msg);
        closeDialog()
        resetQuery()
      }
    }
  })
}

// 新增修改弹窗
const closeDialog = () => {
  ruleFormRef.value.resetFields();
  dialog.visible = false;
}

// 删除
const handleDelete = async (id: number) => {
  await ElMessageBox.confirm("确定要删除吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",

  }).then(async () => {
    let res = await getTaskDel({ id: id }) as any;
    ElMessage.success(res.msg);
    handleQuery();
  }).catch(() => {
    ElMessage({
      type: "info",
      message: "已取消删除",
    });
  });
}

onMounted(() => {
  handleQuery(); // 初始化用户列表数据
});
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">

      <el-col :lg="24" :xs="24">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="素材类型" prop="type">
              <el-select v-model="queryParams.type" placeholder="选择素材类型" clearable style="width: 200px"
                @change="handleQuery">
                <el-option label="图片" :value="1" />
                <el-option label="音频" :value="2" />
                <el-option label="视频" :value="3" />
              </el-select>
            </el-form-item>
            <el-form-item label="素材名称" prop="title">
              <el-input v-model="queryParams.title" placeholder="输入素材名称" clearable style="width: 200px"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery"><i-ep-search />搜索</el-button>
              <el-button @click="resetQuery">
                <i-ep-refresh />
                重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button @click="hanldeOpenDialog()" type="success"><i-ep-plus />新增</el-button>
              </div>
            </div>
          </template>
          <el-table v-loading="loading" :data="userList">
            <el-table-column label="编号" align="center" prop="id" width="100" />
            <el-table-column label="素材名称" align="center" prop="title" />
            <el-table-column label="素材类型" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.type == 1" type="success">图片</el-tag>
                <el-tag v-else-if="scope.row.type == 2" type="success">音频</el-tag>
                <el-tag v-else-if="scope.row.type == 3" type="success">视频</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="pic" label="素材封面" align="center">
              <template #default="scope">
                <img :src="imgUrl + scope.row.image" alt="" style="width: 50px; height: 50px" />
              </template>
            </el-table-column>
            <el-table-column label="链接" align="center" prop="link" />
            <el-table-column label="状态" align="center">
              <template #default="scope">

                <el-tag v-if="scope.row.is_show == 1" type="success">显示</el-tag>
                <el-tag v-else-if="scope.row.is_show == 2" type="success">隐藏</el-tag>

              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" align="center" width="280">
              <template #default="scope">
                <el-button @click="hanldeOpenDialog(scope.row)" type="primary" size="small"><i-ep-edit />编辑</el-button>
                <el-button @click="handleDelete(scope.row.id)" type="danger" size="small"><i-ep-delete />删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page"
            v-model:limit="queryParams.page_size" @pagination="handleQuery" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增修改弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="60%" append-to-body @close="closeDialog">
      <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-width="120px">
        <el-form-item label="素材类型">
          <el-radio-group v-model="formData.type">
            <el-radio :value="1">图文</el-radio>
            <el-radio :value="2">音频</el-radio>
            <el-radio :value="3">视频</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="素材分类名称" prop="title">
          <el-input v-model="formData.title" placeholder="请输入素材分类名称" />
        </el-form-item>
        <el-form-item label="顶级素材分类" prop="pid">
          <el-tree-select value-key="id" placeholder="请输入顶级素材分类" v-model="formData.pid"
            :props="{ children: 'child', label: 'title' }" :data="selectList" check-strictly
            :render-after-expand="false">
          </el-tree-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="formData.sort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item v-if="formData.type > 1" label="链接" prop="link">
          <el-input v-model="formData.link" placeholder="请输入链接" />
        </el-form-item>
        <el-form-item label="图片" prop="url">
          <single-upload @updatepostUrl="updatepostUrl" v-model="formData.url" type="image" />
        </el-form-item>
        <el-form-item label="素材详情" prop="content">
          <div style="border:1px solid #EBEEFF;height: 490px;">
            <editor v-model="formData.content" style="height: 400px; width: 100%;" />
          </div>
        </el-form-item>
        <el-form-item label="素材简介" prop="detail">
          <div style="border:1px solid #EBEEFF;height: 490px;">
            <editor v-model="formData.detail" style="height: 400px; width: 100%;" />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
